package com.zw.knowlege.util;

import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class CommonUtils {

    private CommonUtils(){

    }

    public static boolean nullOrEmpty(String str){
        return (null == str)||(StringUtils.isEmpty(str)) || (str.trim().length() == 0);
    }

    /**
     * 根据字符串获取MD%
     * @param str
     * @return
     */
    public final static String getMd5(String str){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder builder = new StringBuilder();
            for (byte aByte : bytes) {
                builder.append(Integer.toHexString((0x000000FF & aByte) | 0xFFFFFF00).substring(6));
            }
            return builder.toString();

        } catch (NoSuchAlgorithmException e) {
            return getRandomString(32);
        }
    }

    /**
     * 随机生成32位字符串
     * @param length
     * @return
     */
    public static String getRandomString(int length){
        String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0; i<length; ++i){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
